package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yxt.common.sort.MapComparator;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.ui.TextItemOnClickListener;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;
import com.yxt.model.Listener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class TyphoonListActivity extends Activity {
	private List<Map<String,String>> typhoons = new ArrayList<Map<String,String>>();
	private MapComparator comparator = new MapComparator();	
	private String[] from = { "code", "name", "ename", "NF" };
	private int[] to = {R.id.lbl1,R.id.lbl2,R.id.lbl3,R.id.lbl4};
	private String[] keys = {"code","ename"};
	private TyphoonListTableAdapter adapter;
	private ProgressDialog dialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.typhoon_list);   //软件activity的布局	
		ActivityStackControlUtil.add(this);
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		Button btnForward = (Button)findViewById(R.id.btnForward);
		btnForward.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				List<String> typhonlst = adapter.getTyphoons();
				int size = typhonlst.size();
				if (size == 0) {
					Toast.makeText(TyphoonListActivity.this, "请选择台风信息", Toast.LENGTH_LONG).show();
				}
				intent.setClass(getApplicationContext(), TyphoonTrackActivity.class);
				StringBuffer buffer = new StringBuffer();
				for (int i = 0; i < size; i++) {
					if (i > 0)
						buffer.append(",");
					buffer.append(typhonlst.get(i));
				}
				intent.putExtra("tfcode", buffer.toString());
				startActivity(intent);
			}
		});
		initComponent();
	}
	
	private void initComponent(){
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					fillListView("");
					dialog.cancel();
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadTyphoonList();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}
	
	private void downloadTyphoonList() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new TyphoonHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}	
	}
	
	private InputStream getInputStream() throws IOException{
		String server = CommConstant.Sever.TFDATA_SERVER;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"tflist.xml");
		} else {
			URL url = new URL(server + "tfdata/TFList.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}
	
	private class TyphoonHandler extends DefaultHandler {
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("tfinfo".equals(localName)) {
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				typhoons.add(data);
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}	
	
	private void fillListView(String key) {
		if (!"".equals(key)) {
			comparator.setKey(key);
			Collections.sort(typhoons, comparator);
		}

		List<Listener> items = new ArrayList<Listener>();
		for (int i = 0; i < from.length-1; i++) {
			Listener listener = new Listener(to[i],new TextItemOnClickListener(this, TyphoonDataActivity.class));
			items.add(listener);
		}
		
		List<String> keylist = new ArrayList<String>();
		for (int i = 0; i < keys.length; i++) {
			keylist.add(keys[i]);
		}
		
		adapter = new TyphoonListTableAdapter(this,typhoons,R.layout.typhoon_list_item,from,to,items,keylist);
		ListView lstTyphoonList = (ListView) findViewById(R.id.lstTyphoonList);
		lstTyphoonList.setAdapter(adapter);
	}

	public class TyphoonListTableAdapter extends SimpleAdapter {
		private List<Map<String,String>> dataList;
		private List<String> typhoons = new ArrayList<String>();
		private List<Listener> itemListeners = new ArrayList<Listener>();
		private List<String> keyList = new ArrayList<String>();
		private Map<String,String> map = new HashMap<String,String>();
		
		public TyphoonListTableAdapter(Context context, List<Map<String,String>> data,int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			this.dataList = data;
		}

		public TyphoonListTableAdapter(Context context, List<Map<String,String>> data,int resource, String[] from, int[] to, List<Listener> items, List<String> keys) {
			super(context, data, resource, from, to);
			keyList.addAll(keys);
			itemListeners.addAll(items);
			this.dataList = data;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);		 
			int colorPos = position % CommConstant.Config.DEFAULT_TABLE_COLORS.length;
			view.setBackgroundColor(CommConstant.Config.DEFAULT_TABLE_COLORS[colorPos]);
					
			Map<String,String> data = dataList.get(position);
			for (int i = 0; i< itemListeners.size(); i++) {
				Listener item = itemListeners.get(i);
				View v = view.findViewById(item.getId());
				TextItemOnClickListener listener = item.getListener();
				Map<String,String> params = new HashMap<String,String>();
				for (int k = 0; k < keyList.size(); k++) {
					String key = keyList.get(k);
					params.put(key,data.get(key));
				}
				listener.setParameters(params);
				v.setOnClickListener(listener);
			}
			final String code = data.get("code");		
			
			final LinearLayout layout = (LinearLayout)view.findViewById(R.id.pnlRight);
			layout.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {
					if (typhoons.size() >= CommConstant.Typhoon.TYPHOON_MAX_COUNT) {
						Toast.makeText(TyphoonListActivity.this, "最多只能选取五个台风信息", Toast.LENGTH_LONG).show();
						return;
					}
					ImageView imageTyphoon = (ImageView)layout.findViewById(R.id.imageTyphoon);
					if (map.containsKey(code)) {
						typhoons.remove(code);
						imageTyphoon.setImageResource(R.drawable.btn_check_off_pressed);
					} else {
						typhoons.add(code);
						map.put(code, code);
						imageTyphoon.setImageResource(R.drawable.btn_check_on_pressed);
					}
				}
			});
			return view;
		}
		
		public List<String> getTyphoons() {
			return typhoons;
		}
	}

	protected void onDestroy() {
		super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}